package com.qdev.apps.core.webwork.validator;

import java.util.Map;

import com.opensymphony.webwork.validators.ScriptValidationAware;


/**
 * @author Peter
 * @since 2005-7-20
 * @version $Revision 1.0$
 */
public class JavaScriptStringLengthFieldValidator extends StringLengthFieldValidator implements ScriptValidationAware{
    public String validationScript(Map parameters) {
        String field = (String) parameters.get("name");
        int maxLength = getMaxLength();
        StringBuffer js = new StringBuffer();

        js.append("value = form.elements['" + field + "'].value;\n");
        js.append("len = 0;\n");
        js.append("for(i=0; i<value.length; i++){\n");
        js.append("\ts=value.charAt(i);\n");
        js.append("\tif(escape(s).length>=6)\n");
        js.append("\t\tlen+=2;\n");
        js.append("\telse\n");
        js.append("\t\tlen+=1;\n");
        js.append("\t}\n");
        js.append("if (len > "+maxLength+") {\n");
        js.append("\talert('" + getMessage(null) + "');\n");
        js.append("\treturn '" + field + "';\n");
        js.append("}\n");
        js.append("\n");

        return js.toString();
    }
}